package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/7 15:21
 * https://leetcode-cn.com/problems/spiral-matrix-ii/
 */
public class Title59 {

    /**                        up
     *                   [left,   right]
     * @param n              down
     * @return
     */
    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        int up = 0, down = n - 1;
        int left = 0, right = n - 1;
        int count= 0;
        int sum = n * n;
        while (count < sum) {
            //左到右
            for (int j = left; j <= right && count < sum; j++) {
                result[up][j] = ++count;
            }
            up++;
            //从上到下
            for (int i = up; i <= down && count < sum; i++) {
                result[i][right] = ++count;
            }
            right--;
            //从右到左
            for (int j = right; j >= left && count < sum; j--) {
                result[down][j] = ++count;
            }
            down--;
            //从下到上
            for (int i = down; i >= up; i--) {
                result[i][left] = ++count;
            }
            left++;
        }
        return result;
    }














    public static int[][] generateMatrix1(int n) {
        int count = 0;
        int[][] result = new int[n][n];
        int up = 0, down = n - 1, left = 0, right = n - 1;
        int sum = n * n;
        while (count < sum) {
            //左到右
            for (int i = left; i <= right && count < sum; i++) {
                result[up][i] = ++count;
            }
            up++;
            //从上到下
            for (int i = up; i <= down && count < sum; i++) {
                result[i][right] = ++count;
            }
            right--;
            //从右到左
            for (int i = right; i >= left && count < sum; i--) {
                result[down][i] = ++count;
            }
            down--;
            //从下到上
            for (int i = down; i >= up && count < sum; i--) {
                result[i][left] = ++count;
            }
            left++;
        }
        return result;
    }



    public static void main(String[] args) {
        generateMatrix1(3);
    }
}
